package ordinaryArray;

import org.junit.Test;

/*
 *@description
 *@author hkfan
 *@version 1.0
 *@create 2025/5/23 17:24
 */
public class LeetCode_27 {

    @Test
    public void test(){
        System.out.println(removeElement(new int[]{0,1,2,2,3,0,4,2},2));
    }


    public int removeElement(int[] nums, int val) {
        //1. 定义快慢指针
        int s=0,f=0;
        //2. 循环遍历
        while (s<nums.length && f<nums.length){

            s = next(s,nums,true,val);  //第一个相同的
            f = next(s,nums,false,val);
            if (f< nums.length){
                nums[s]=nums[f];
                nums[f]=val;
            }
        }
        return s;
    }

    private int next(int i, int[] nums, boolean flag, int val) {
        if (flag){  //!=k
            while (i<nums.length && nums[i]!=val){
                i++;
            }
        } else {    //==k
            while (i<nums.length && nums[i]==val){
                i++;
            }
        }
        return i;
    }
}
